const express = require('express')
const router = express.Router()
const bcrypt = require('bcryptjs')
const db = require('../db/index.js')
const expressJoi = require('@escook/express-joi')
const {update_userinfo_schema,update_password_schema,update_avatar_schema} = require('../schema/user.js')

// 获取用户基本信息
router.get('/userinfo',(req,res)=>{
    const sql = 'select id,username,nickname,email,user_pic from ev_users where id=?'
    db.query(sql,req.user.id,(err,results)=>{
        if(err){
            return res.send({status:1,message:err.message})
        }
        if(results.length != 1){
            return res.send({status:1,message:'获取用户失败'})
        }
        res.send({
            status:0,
            message:'获取用户信息成功',
            data:results[0]
        })
    })   
})

// 更新用户基本信息
router.post('/userinfo',expressJoi(update_userinfo_schema),(req,res)=>{
    const sql = 'update ev_users set ? where id=?'
    db.query(sql,[req.body,req.body.id],(err,results)=>{
        if(err){
            // console.log(err);
            return res.send({status:1,message:err.message})   //错误信息出不来
        }
        if(results.affectedRows !== 1){
            return res.send({status:1,message:'修改个人信息失败'})
        }
        return res.send({status:0,message:'修改信息成功'})
    })
})


// 重置密码的路由
router.post('/updatepwd',expressJoi(update_password_schema),(req,res)=>{
    const sql = 'select * from ev_users where id=?'
    db.query(sql,req.user.id,(err,results)=>{
        if(err){
            return res.send({status:1,message:err.message})
        }
        if(results.length !== 1){
            return res.send({status:1,message:'用户不存在'})
        }
        // 判断提交的旧密码是否正确
        const bcrypt = require('bcryptjs')
        const compareResult = bcrypt.compareSync(req.body.oldPwd,results[0].password)
        if(!compareResult){
            return res.send({status:1,message:'原密码错误'})
        }

        // 对新密码加密更新到数据库
        const sql = 'update ev_users set password=? where id=?'
        const newPwd = bcrypt.hashSync(req.body.newPwd,10)

        // 执行sql语句根据id更新密码
        db.query(sql,[newPwd,req.user.id],(err,results)=>{
            if(err){
                return res.send({status:1,message:err.message})
            }
            // results.length结果是undefine
             
            if(results.affectedRows !== 1){
                return res.send({status:1,message:'更新密码失败'})
            }
            res.send({status:0,message:'更新密码成功'})
        })
    })
})

// 更换头像的功能
router.post('/update/avatar',expressJoi(update_avatar_schema),(req,res)=>{
    const sql = 'update ev_users set user_pic=? where id=?'
    db.query(sql,[req.body.avatar,req.user.id],(err,results)=>{
        if(err){
            return res.send({status:1,message:err.message})
        }
        if(results.affectedRows !== 1){
            return res.send({status:1,message:'更新头像失败'})
        }
        return res.send({status:0,message:'更新头像成功'})
    })
})


module.exports = router